angular.module("controller.main", ["services"])
.controller("mainCtrl", ["$rootScope", "alertManager", "constants", function($rootScope, alertManager, constants) {
	$rootScope.constants = constants;
	$rootScope.alerts = [];
	$rootScope.removeAlert = alertManager.removeAlert;
	$rootScope.$on('$stateChangeStart', function(evt, toState) {
		$rootScope.state = toState;
	});
}])
.controller("feastBookingCtrl", ["$scope", "$state", "$rootScope", "$interval", "$window", "$filter", "notificationService", "constants", "apiService", function($scope, $state, $rootScope, $interval, $window, $filter, notificationService, constants, apiService) {
	$scope.data = {};
	$rootScope.state = $state.current;
	
	jim = new JMessage();
	var initInfo = notificationService.getInitInfo();
	var username = notificationService.getUsername();
	var password = notificationService.getPassword();
	
	$scope.unreadCnt = 0;
	$scope.notifications = [];
	
	function saveNotifications(notifications) {
		apiService.saveNotification(notifications);
	}
	
	jim.init(initInfo).onSuccess(function() {
		
		jim.login({
			username: username,
			password: password,
			//is_md5: true
		}).onSuccess(function(data) {
			
			jim.onSyncConversation(function(data) {
				$scope.$apply(function() {
					var msgs = data.messages;
					msgs && msgs.forEach(function(msg) {
						$scope.notifications.push({
							from: message.from_username,
							content: message.content.msg_body.text
						});
					});
					if(!!msgs && msgs.length > 0) {
						saveNotifications(msgs.map(function(msg) {
							return {
								from: msg.from,
								message: msg.content,
								read: 1,
								createdTime: $filter('date')(new Date(), 'yyyy-MM-dd HH:mm')
							};
						}));
					}
					$scope.unreadCnt = $scope.notifications.length;
				});
			}, function(message) {
				console.log(message);
			});
			
			jim.onMsgReceive(function(data) {
				console.log(jim.getUnreadMsgCnt({username: username}));
				$scope.$apply(function() {
					var msgs = data.messages.map(function(message) {
						return {
							from: message.from_username,
							content: message.content.msg_body.text
						};
					});
					msgs && msgs.forEach(function(msg) {
						$scope.notifications.unshift(msg);
					});
					saveNotifications(msgs.map(function(msg) {
						return {
							from: msg.from,
							message: msg.content,
							read: 1,
							createdTime: $filter('date')(new Date(), 'yyyy-MM-dd HH:mm')
						};
					}));
					$scope.unreadCnt = $scope.notifications.length;
				});
			}, function(message) {
				console.log(message);
			});
			
		}).onFail(function(data) {
			console.log(data.message);
		});
	}).onFail(function(data) {
		console.log(data.message);
	});

}])